from django import template
from django.db.models import Model

register = template.Library()

@register.filter
def get_item(item, key):
    """从字典或对象中获取指定键的值"""
    if isinstance(item, dict):
        return item.get(key)
    elif isinstance(item, Model):
        return getattr(item, key, None)
    elif isinstance(item, (list, tuple)) and isinstance(key, int):
        return item[key] if 0 <= key < len(item) else None
    return None

@register.filter
def get_primary_key(columns):
    """获取主键列名，假设第一列是主键"""
    if isinstance(columns, (list, tuple)) and len(columns) > 0:
        return columns[0]
    return None

@register.filter
def get_primary_key_value(item, columns):
    """获取主键值"""
    if not columns or not isinstance(columns, (list, tuple)) or len(columns) == 0:
        return None
    
    primary_key = columns[0]
    return get_item(item, primary_key)